package com.chunxuan.langquan.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.chunxuan.langquan.R;
import com.chunxuan.langquan.base.BaseResult2;
import com.chunxuan.langquan.base.Global;
import com.chunxuan.langquan.dao.bean.Banner;
import com.chunxuan.langquan.dao.bean.ProductEntity;
import com.chunxuan.langquan.dao.http.APIRetrofit;
import com.chunxuan.langquan.dao.http.APIRetrofit2;
import com.chunxuan.langquan.support.util.GlideUtil;
import com.chunxuan.langquan.support.util.Logg;
import com.chunxuan.langquan.ui.activity.GuidActivity;
import com.chunxuan.langquan.ui.activity.WebViewActivity;
import com.chunxuan.langquan.ui.activity.store.ProductCategoryActivity;
import com.chunxuan.langquan.ui.activity.store.ProductDetailActivity;
import com.chunxuan.langquan.ui.activity.store.ShoppingCarActivity;
import com.chunxuan.langquan.ui.activity.store.adapter.BaseAdapter;
import com.chunxuan.langquan.ui.activity.store.adapter.BaseViewHolder;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.base.BaseFragment;
import com.ruitu.arad.util.HandlerUtil;
import com.ruitu.arad.util.StringUtils;
import com.ruitu.arad.util.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.SearchView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

// 首页
public class Home3Fragment extends BaseFragment implements HandlerUtil.OnReceiveMessageListener {
    //    private Banner banner;
    private static Home3Fragment fragment;
    private ImageView iv_shopping_market_category;// 消息
    private ImageView iv_shopping_car,iv_back_vv;
    private RecyclerView rlv;
    private Adapter mAdapter;
    private SearchView searchView;


    private ViewPager vp;
    private List<Banner> bannerList = new ArrayList<>();// banner的数据
    private VpAdapter adapter;// banner

    private int currIndex = 0;
    private HandlerUtil.HandlerHolder handler;

    public Home3Fragment() {

    }

    public static Home3Fragment newInstance() {
        if (fragment == null) {
            fragment = new Home3Fragment();
            Bundle args = new Bundle();
            fragment.setArguments(args);
        }
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new HandlerUtil.HandlerHolder(this);
    }
    // 请求首页banner
    private Disposable reqBannerList() {
        return APIRetrofit2.getDefault().reqBannerList(Global.HEADER, 3)
                .compose(RxUtil.<BaseResult2<List<Banner>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<Banner>>>() {
                    @Override
                    public void accept(BaseResult2<List<Banner>> listBaseResult2) throws Exception {
                        hideProgress();
                        if (listBaseResult2.isSuccess()) {

                        } else {

                        }
                        bannerList = listBaseResult2.getData();
                        adapter.notifyDataSetChanged();

                        handler.sendEmptyMessageDelayed(21031052, 5000);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }
    @Override
    public void handlerMessage(Message msg) {
        if (msg.what == 21031052) {// 轮播
            handler.removeMessages(21031052);
            try {
                currIndex++;
                if (currIndex >= bannerList.size()) {
                    currIndex = 0;
                }
                vp.setCurrentItem(currIndex, true);
                handler.sendEmptyMessageDelayed(21031052, 5000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.activity_shoping_market, container, false);
        iv_shopping_market_category = v.findViewById(R.id.iv_shopping_market_category);
        iv_shopping_car = v.findViewById(R.id.iv_shopping_market_cart);
        rlv = v.findViewById(R.id.rv_shopping_market_list);
        searchView = v.findViewById(R.id.sv_shopping_market);
        vp = v.findViewById(R.id.vp);
        iv_back_vv = v.findViewById(R.id.iv_back_vv);
        adapter = new VpAdapter();
        vp.setAdapter(adapter);
        reqBannerList();// 请求banner列表
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                search(query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
        mAdapter = new Adapter();
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2);
        rlv.setLayoutManager(gridLayoutManager);
        rlv.setAdapter(mAdapter);
        setListeners();
        requestHome();
        return v;
    }
    // banner adapter
    private class VpAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return bannerList.size();
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            ImageView iv = new ImageView(getActivity());
            final ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            iv.setLayoutParams(params);
            iv.setScaleType(ImageView.ScaleType.CENTER_CROP);

//            iv.setImageResource(R.drawable.home_top_banner);
            GlideUtil.loadImg(bannerList.get(position).getAd_image(), iv);

            container.addView(iv);
            iv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(!TextUtils.isEmpty(bannerList.get(position).getAd_url())){
                        Intent intent=new Intent(getContext(), WebViewActivity.class);
                        intent.putExtra("ad_url",bannerList.get(position).getAd_url());
                        startActivity(intent);
                    }
                }
            });
            return iv;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            container.removeView((ImageView) object);
        }
    }
    private void setListeners() {
        setOnClickListener(iv_shopping_market_category, iv_shopping_car,iv_back_vv);
        vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currIndex = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v == iv_shopping_market_category) {// 搜索
//            startActivity(SearchActivity.class);
            startActivity(ProductCategoryActivity.class);
        }
        if (v == iv_shopping_car) {
            startActivity(ShoppingCarActivity.class);
        }
        if (v == iv_back_vv) {
            startActivity(GuidActivity.class);
            getActivity().finish();
        }
    }

    @SuppressLint("CheckResult")
    public void requestHome() {
        showProgress();

        APIRetrofit.getDefault().requestStoreHome(Global.HEADER,1,1000000)
                .compose(RxUtil.<BaseResult2<List<ProductEntity>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<ProductEntity>>>() {
                    @Override
                    public void accept(BaseResult2<List<ProductEntity>> result2) throws Exception {
                        hideProgress();
                        if (result2.isSuccess()) {
                            final List<ProductEntity> categorys = result2.getData();
                            if (!isDataEmpty(categorys)) {
                                mAdapter.setDatas(categorys);

                            }
                        } else {
                            ToastUtils.showShort(result2.getMsg());
                        }
//                        Logg.i("reqUserInfo.result2.getMsg()" + result2.getMsg());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("获取首页数据失败");
                    }
                });
    }


    @SuppressLint("CheckResult")
    public void search(String search){
        if (StringUtils.isEmpty(search)){
            requestHome();
        }else {
            APIRetrofit.getDefault().searchProduct(Global.HEADER,search)
                    .compose(RxUtil.<BaseResult2<List<ProductEntity>>>subIoObMain())
                    .subscribe(new Consumer<BaseResult2<List<ProductEntity>>>() {
                        @Override
                        public void accept(BaseResult2<List<ProductEntity>> result2) throws Exception {
                            hideProgress();
                            if (result2.isSuccess()) {
                                final List<ProductEntity> categorys = result2.getData();
                                if (!isDataEmpty(categorys)) {
                                    mAdapter.setDatas(categorys);

                                }
                            } else {
                                ToastUtils.showShort(result2.getMsg());
                            }
//                        Logg.i("reqUserInfo.result2.getMsg()" + result2.getMsg());
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            hideProgress();
                            throwable.printStackTrace();
                            ToastUtils.showShort("获取首页数据失败");
                        }
                    });
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    static class Adapter extends BaseAdapter<ProductEntity> {

        @NonNull
        @Override
        public BaseViewHolder<ProductEntity> onCreateViewHolder(@NonNull final ViewGroup parent,
                                                                int viewType) {
            LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
            final ViewHolder viewHolder;
                View view = layoutInflater.inflate(R.layout.item_product_list, parent,
                        false);
            GridLayoutManager.LayoutParams lp = (GridLayoutManager.LayoutParams) view.getLayoutParams();
            if (viewType % 2 == 0) {
                lp.leftMargin = 30;
                lp.rightMargin = 8;
            } else if (viewType % 2 == 1) {
                lp.leftMargin = 8;
                lp.rightMargin = 30;
            }
            lp.topMargin = 10;
            view.setLayoutParams(lp);
                viewHolder = new ViewHolder(view);
            viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ProductDetailActivity.actionStart(parent.getContext(),
                            getDatas().get(viewHolder.getAdapterPosition()).getProduct_id());
                }
            });
            return viewHolder;
        }

        @Override
        public int getItemViewType(int position) {
            return position;
        }
    }

    static class ViewHolder extends BaseViewHolder<ProductEntity> {
        ImageView iv;
        TextView tvTitle,tvPrice;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            iv = itemView.findViewById(R.id.iv_shopping_market_cover);
            tvTitle=itemView.findViewById(R.id.tv_title);
            tvPrice=itemView.findViewById(R.id.tv_price);
        }

        @Override
        public void bindViewHolder(ProductEntity value) {
            GlideUtil.loadImg(value.getImage(), iv);
            tvTitle.setText(value.getTitle());
            tvPrice.setText("￥"+value.getSales_price());
        }
    }
}